<template>
  <el-card class="timetable-upload">
    <template #header>
      <h3>上传本学期课表</h3>
    </template>
    <el-form :model="form" ref="formRef" label-width="120px">
      <el-form-item label="学期" prop="semester">
        <el-input v-model="form.semester" placeholder="例如：2023-2024学年第二学期"></el-input>
      </el-form-item>
      <el-form-item label="课表文件" prop="file">
        <el-upload
          class="upload-demo"
          :action="uploadAction" 
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
          :limit="1"
          :auto-upload="false"
          ref="uploadRef"
          @change="handleFileChange" 
        >
          <el-button size="small" type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">支持Excel、PDF格式，不超过5MB</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="备注">
        <el-input type="textarea" v-model="form.remark" :rows="2" placeholder="选填：课表说明"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitUpload">提交上传</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { uploadTimetable } from '@/api/classLeader';
import { useUserStore } from '@/store/user';


const userStore = useUserStore();
const formRef = ref(null);
const uploadRef = ref(null);
const form = reactive({
  semester: '',
  file: null, // 存储选中的文件
  remark: ''
});

// 新增：文件选择变化时更新form.file
const handleFileChange = (file) => {
  form.file = file.raw; // 通过 raw 获取原始文件对象
};

const submitUpload = async () => {
  await formRef.value.validate(); // 触发表单验证

  if (!form.file) { // 检查form.file是否存在
    ElMessage.warning('请选择课表文件');
    return;
  }

  try {
    const formData = new FormData();
    formData.append('semester', form.semester);
    formData.append('file', form.file); 
    formData.append('remark', form.remark);
    formData.append('studentId', userStore.userInfo.studentId);

    await uploadTimetable(formData);
    ElMessage.success('课表上传成功');
    resetForm();
  } catch (error) {
    ElMessage.error(error.message || '上传失败，请重试');
  }
};

const resetForm = () => {
  formRef.value.resetFields();
  uploadRef.value.clearFiles(); // 清除上传组件文件
  form.file = null; // 重置文件引用
};

const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.ms-excel' || 
                  file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const isPDF = file.type === 'application/pdf';
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isExcel && !isPDF) {
    ElMessage.error('上传文件只能是Excel或PDF格式');
    return false; // 阻止文件添加到上传列表
  }

  if (!isLt5M) {
    ElMessage.error('上传文件大小不能超过5MB');
    return false; // 阻止文件添加到上传列表
  }

  // 允许文件时，不做额外操作，由handleFileChange处理文件赋值
  return true;
};

// 上传成功/失败处理（可根据需要保留）
const handleUploadSuccess = () => {
  ElMessage.success('文件预上传成功');
};

const handleUploadError = () => {
  ElMessage.error('文件预上传失败');
};
</script>